package com.example.lotterysystem.service.impl;

import com.example.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import com.example.lotterysystem.common.exception.ServiceException;
import com.example.lotterysystem.service.PictureService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Component
public class PictureServiceImpl implements PictureService {

    @Value("${pic.local-path}")
    private String localPath;

    @Override
    public String savePicture(MultipartFile multipartFile) {
        //创建目录(一个路径层次)，只是创建，无法保证已有该目录
        File dir=new File(localPath);
        //判断有无该目录，无则创建
        if (!dir.exists()){
            dir.mkdirs();
        }
        //创建索引
        //将图图片的名称作为索引
        String filename = multipartFile.getOriginalFilename();
        assert filename!=null;
        String suffix = filename.substring(filename.lastIndexOf("."));
        //UUID.randomUUID()用来生成全员唯一标识符
        filename = UUID.randomUUID()+suffix;

        //保存图片
        try {
            multipartFile.transferTo(new File(localPath+"/"+filename));
        } catch (IOException e) {
            throw new ServiceException(ServiceErrorCodeConstants.PICTURE_UPLOAD_ERROR);
        }
        return filename;
    }
}
